package com.fwj.core.common.common;

import com.alibaba.fastjson.JSONObject;
import com.fwj.core.common.constant.CoreConstant;
import com.fwj.user.entity.user.UserBaseInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @Author: fwj
 * @Data: 2021/12/18 11:15
 * @Version 1.0
 * @Description:
 */


public class CommonUtils {

    //添加日志工厂
    private static final Logger LOGGER = LoggerFactory.getLogger(CommonUtils.class);

    /**
     * 判断是否为空，空则返回true，否则返回false
     * */
    public static boolean isEmpty(Object object) {
        boolean result = true;
        if (object == null) {
            return true;
        }
        if (object instanceof String) {
            result = (object.toString().trim().length() == 0) || object.toString().trim().equals("null");
        } else if (object instanceof Collection) {
            result = ((Collection) object).size() == 0;
        } else {
            result = (object == null) || (object.toString().trim().length() < 1) ? true : false;
        }
        return result;
    }

    /**
     * 判断是否为空，空则返回false，否则返回true
     * */
    public static boolean isNotEmpty(Object object) {
        return !isEmpty(object);
    }

    public static Long generateUniqueUserNumber() {
        IdWorker idWorker = new IdWorker();
        return idWorker.nextId();
    }

    public static Long generateUniqueNumber() {
        return generateUniqueUserNumber();
    }

    public static UserBaseInfo getUserBaseInfo(String authSession){
        try {
            final String Redis_Key = authSession;
            UserBaseInfo userBaseInfo = null;
            if (RedisUtil.exists(Redis_Key)){
                String userCacheInfo = RedisUtil.getString(Redis_Key);
                if (CommonUtils.isNotEmpty(userCacheInfo)){
                    userBaseInfo = JSONObject.parseObject(userCacheInfo,UserBaseInfo.class);
                    return userBaseInfo;
                }
            }
        } catch (Exception e){
            LOGGER.info(e.toString());
        }
        return null;
    }


    /**
     * @Description 获取登录信息
     * @Param: request
     * @Author fwj
     * @return java.lang.String
     * @Createtime 2022/4/11
     */
    public static String getAuthSession(HttpServletRequest request) {
        String authSession = null;
        //取出Cookie数据
        if (CommonUtils.isNotEmpty(authSession = CookieUtil.getCookie(request, CoreConstant.AUTH_SESSION))){
            return authSession;
        }
        //取出header数据
        if (CommonUtils.isNotEmpty(authSession = request.getHeader("authSession"))){
            return authSession;
        }
        return null;
    }
}
